package cn.tedu.route;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;

//模拟路由模式的消费者
public class RouteConsumer {
    public static void main(String[] args) throws Exception {
        //1.创建连接和channel
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1");
        cf.setUsername("guest");
        cf.setPassword("guest");
        Connection nc = cf.newConnection();
        Channel cc = nc.createChannel();
        //第一个参数是交换机名称；第二个参数是交换机类型
        cc.exchangeDeclare("type_direct", BuiltinExchangeType.DIRECT);
        String queueName = cc.queueDeclare().getQueue();
        //使用绑定键绑定交换机和队列，一个队列可以有多个绑定键
        System.out.print("输入绑定键，用空格隔开:");
        String str = new Scanner(System.in).nextLine();
        //用空格切分str，得到多个绑定键的数组
        String[] bingDingKeys = str.split("\\s+");
        //遍历bingDingKeys，绑定交换机和队列
        for (String bingDingKey : bingDingKeys) {
            cc.queueBind(queueName,"type_direct",bingDingKey);
        }
        //接受并处理消息
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                String msg = new String(delivery.getBody());
                System.out.println("接收到消息："+msg);
                System.out.println("消息处理完毕");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        cc.basicConsume(queueName,true,deliverCallback,cancelCallback);
    }
}
